package com.woniu.humanresource.config;

import com.woniu.humanresource.exception.AccessDeniedHandlerImpl;
import com.woniu.humanresource.exception.AuthenticationEntryPointImpl;
import com.woniu.humanresource.filter.JWTAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    JWTAuthenticationFilter jwtAuthenticationFilter;

    //认证管理器
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    //密码加密
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


    //主配置方法
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors();

        http.csrf().disable()  //禁用跨站响应伪造 必须配置要不访问不了
                //用token就不需要session 把session的策略改为禁用
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests() //开启请求权限管理
                .antMatchers("/login","/validateInterviewer","/images/**").anonymous() ;//匿名访问 不用认证就能访问 有token不能访问
                //.antMatchers("/login").permitAll() //不用认证就能访问 就是放行 前后端不分离对静态资源放行
                //.anyRequest().authenticated(); //其他的拦截认证

        //权限统一管理
        //权限异常
        http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPointImpl())
                //访问异常
                .accessDeniedHandler(new AccessDeniedHandlerImpl())
                .and().cors();

        //配置拦截器
        http.addFilterAfter(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
